// Copyright (c) Appeon. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.

using System;
using Newtonsoft.Json;

namespace SnapObjects.Data
{
    internal class JsonUnPackerParser<T> : IDataUnpackerParser<T>
    {
        public T Parse(string value)
        {
            if (value != null)
            {
                var provider = JsonProviderFactory.Create();

                if (typeof(T) == typeof(string))
                {
                    return (T)(object)value;
                }
                else if (typeof(T) == typeof(bool))
                {
                    return provider.DeserializeObject<T>(value.ToLower());
                }
                else if (typeof(T) == typeof(DateTime) || typeof(T) == typeof(DateTime?))
                {
                    return (T)Convert.ChangeType(value, typeof(DateTime));
                }
                else
                {
                    return provider.DeserializeObject<T>(value);
                }
            }
            else
            {
                return default;
            }
        }
    }

    internal class JsonUnPackerParser : IDataUnpackerParser
    {
        private readonly Type _dataType;

        public JsonUnPackerParser(Type dataType)
        {
            _dataType = dataType;
        }

        public object Parse(string value)
        {
            if (_dataType == typeof(string))
            {
                return value;
            }
            else
            {
                return JsonProviderFactory.Create().DeserializeObject(value, _dataType);
            }
        }
    }
}
